import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter, menu } from '@/router'
import { menus } from '@/router/menu'
import {error} from "autoprefixer/lib/utils";

const getDefaultState = () => {
    return {
        token: getToken(),
        name: '',
        avatar: '',
        perms: {},
        tenantId: null
    }
}

const state = getDefaultState()
const userPasswordList = [
  {name: 'admin', admin: 'admin123'},
  {name: 'media', media: 'channel123'}
]
const userNameList = ['admin', 'media']
const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_PERMS: (state, perms) => {
        state.perms = perms
    },
    SET_TENANT_ID: (state, tenantId) => {
        state.tenantId = tenantId
    }
}

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { username, password } = userInfo
        return new Promise((resolve, reject) => {
          let pass = false
          if (userNameList.includes(username)) {
            userPasswordList.forEach(item => {
              if (item[username] === password) {
                pass = true
                commit('SET_TOKEN', username)
                setToken(username)
                resolve()
              }
            })
          } else {
            pass = false
          }
          if (!pass) {
            reject(error)
          }
        }).catch(error => {
            reject(error)
        })
    },

    // user logout
    logout({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {
            commit('SET_TOKEN', '')
            removeToken() // must remove  token  first
            sessionStorage.clear()
            localStorage.clear()
            resolve()
        }).catch(error => {
            reject(error)
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken() // must remove  token  first
            commit('SET_TOKEN', '')
            resolve()
        })
    },

    async fetchPageList({ commit, dispatch }, token) {
        const menuList = menus
        resetRouter()
        const accessRoutes = await dispatch('permission/generateRoutes', { menuList }, { root: true })
        router.addRoutes(accessRoutes)
        dispatch('tagsView/delAllViews', null, { root: true })
        return new Promise(resolve => {
            if (accessRoutes.length > 0) {
                resolve(accessRoutes)
            }
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
